package com.hackerchat.client;

import java.awt.BorderLayout;
import java.awt.Panel;
import java.awt.TextArea;
import java.awt.TextField;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;

import com.hackerchat.utils.SCConstants;

public class SCClient extends Panel implements Runnable {

	private static final long serialVersionUID = 1L;
	private TextField tf = new TextField();
	private TextArea ta = new TextArea();
	private Socket socket;
	private DataOutputStream dout;
	private DataInputStream din;

	public SCClient() {
		setLayout( new BorderLayout() );
		add( "North", tf );
		add( "Center", ta );
		tf.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				processMessage(e.getActionCommand());
			}
		});
		
		try {
			socket = new Socket( SCConstants.SERVER, SCConstants.PORT );
			System.out.println("connected to " + socket);
			din = new DataInputStream(socket.getInputStream());
			dout = new DataOutputStream(socket.getOutputStream());
			new Thread(this).start();
		} catch (IOException ie) {
			System.out.println(ie);
		}
	}

	// Gets called when the user types something
	private void processMessage(String message) {
		try {
			// Send it to the server
			dout.writeUTF(message);
			// Clear out text input field
			tf.setText("");
		} catch (IOException ie) {
			System.out.println(ie);
		}
	}

	// Background thread runs this: show messages from other window
	public void run() {
		try {
			// Receive messages one-by-one, forever
			while (true) {
				// Get the next message
				String message = din.readUTF();
				// Print it to our text window
				ta.append(message + "\n");
			}
		} catch (IOException ie) {
			System.out.println(ie);
		}
	}
}
